import {stringify} from 'querystring';
import type {Reducer, Effect} from 'umi';
import {history} from 'umi';
import {accountLogin} from '@/services/login';
import {getPageQuery} from '@/utils/utils';
import {message, notification} from 'antd';
import {setTokens, clearTokens, getAccessToken} from '@/utils/token'
import api from '@/utils/api'
import request from "@/utils/request";
import stringUtil from '@/utils/stringUtil'


export type StateType = {
  accessToken?: string,
  tokenType?: string,
  refreshToken?: string,
  expiresIn?: number,
  scope?: string,
  type?: 'account' | 'mobile'
  error?: string,
  errorDescription?: string,
};
// 暂时不处理手机登录
export type LoginModelType = {
  namespace: string;
  state: StateType;
  effects: {
    login: Effect;
    logout: Effect;
  };
  reducers: {
    changeLoginStatus: Reducer<StateType>;
  };
};

const Model: LoginModelType = {
  namespace: 'login',

  // 该 Model 当前的状态
  state: {
    accessToken: '',
    tokenType: '',
    refreshToken: '',
    expiresIn: 0,
    scope: '',
    type: 'account'
  },

  effects: {
    // 登录
    * login({payload}, {call, put}) {
      const response = yield call(accountLogin, payload);
      yield put({
        type: 'changeLoginStatus',
        payload: response,
      });
      // console.log(response)
      // console.log(response.status)
      // 数据成功返回，即 response.status=200时，为undefined
      if (response.status === undefined) {
        if (response.access_token) {
          console.log(window.location.href)
          const urlParams = new URL(window.location.href);
          const params = getPageQuery();
          message.success('登录成功！');
          // 刷新跳转，这样每次登陆都可以重新获取菜单路由和当前用户，放弃：history.replace(redirect || '/');
          let {redirect} = params as { redirect: string };
          if (redirect) {
            const redirectUrlParams = new URL(redirect);
            if (redirectUrlParams.origin === urlParams.origin) {
              redirect = redirect.substr(urlParams.origin.length);
              if (redirect.match(/^\/.*#/)) {
                redirect = redirect.substr(redirect.indexOf('#') + 1);
              }
              window.location.href = redirect;
            }
          } else {
            window.location.href = '/';
          }
        } else {
          notification.error({
            message: `请求出错 [${response.code}]`,
            description: response.msg,
          });
        }
      }
    },

    // 登出
    logout() {
      const {redirect} = getPageQuery();
      if (window.location.pathname !== '/user/login' && !redirect) {
        const accessToken = getAccessToken();
        // localStorage中查询为空，证明已经过期了，直接清空，不掉后端
        if (stringUtil.isEmpty(accessToken)) {
          // 去除tokens
          clearTokens()
          // history替换
          history.replace({
            pathname: '/user/login',
            search: stringify({
              redirect: window.location.href,
            }),
          });
          return;
        }
        // 调用后台接口
        request(api.logout, {
            method: 'GET',
            params: {token: accessToken.split(" ")[1]}
          }
        ).then(data => {
          if (data.code === 1) {
            // 去除tokens
            clearTokens()
            // history替换
            history.replace({
              pathname: '/user/login',
              search: stringify({
                redirect: window.location.href,
              }),
            });
          }
        });
      }
    },
  },

  reducers: {
    changeLoginStatus(state, {payload}) {
      if (stringUtil.isNotEmpty(payload.access_token)) {
        setTokens(payload);
      }
      return {
        ...state,
        accessToken: payload.access_token,
        tokenType: payload.token_type,
        refreshToken: payload.refresh_token,
        expiresIn: payload.expires_in,
        scope: payload.scope,
        type: 'account',
        error: payload.error,
        errorDescription: payload.error_description,
      };
    },
  },
};

export default Model;
